package main

import (
	"bufio"
	"bytes"
	"fmt"
	"io"
	"log"
	"os"
	"os/exec"
	"os/signal"
	"syscall"

	MQTT "github.com/eclipse/paho.mqtt.golang"
	gomail "gopkg.in/gomail.v2"
)

const ShellToUse = "bash"

func Shellout(command string) (error, string, string) {
	var stdout bytes.Buffer
	var stderr bytes.Buffer
	cmd := exec.Command(ShellToUse, "-c", command)
	cmd.Stdout = &stdout
	cmd.Stderr = &stderr
	err := cmd.Run()
	return err, stdout.String(), stderr.String()
}
func clearDocker() {

	err, out, _ := Shellout("docker kill $(docker ps -a -q)")
	if err == nil {
		fmt.Println(out)
	}
	err, out, _ = Shellout("docker rm $(docker ps -a -q)")
	if err == nil {
		fmt.Println(out)
	}
	err, out, _ = Shellout("docker rmi $(docker images -q)")
	if err == nil {
		fmt.Println(out)
	}
}
func pullDocker() {
	err, out, _ := Shellout("docker run -p 49160:8080 -d registry.cn-hangzhou.aliyuncs.com/wenchangshou/di_test")
	if err == nil {
		fmt.Println(out)
	}

}
func lineCounter(r io.Reader) (int, error) {
	buf := make([]byte, 32*1024)
	count := 0
	lineSep := []byte{'\n'}

	for {
		c, err := r.Read(buf)
		count += bytes.Count(buf[:c], lineSep)

		switch {
		case err == io.EOF:
			return count, nil

		case err != nil:
			return count, err
		}
	}
}
func sendMail() {
	// addresses := make([]string, len(array))
	// for i, recipient := range array {
	// 	addresses[i] = m.FormatAddress(recipient, "")
	// }
	file, err := os.Open("mail.txt")
	if err != nil {
		log.Fatal(err)
	}
	defer file.Close()
	scanner := bufio.NewScanner(file)
	var address []string
	for scanner.Scan() { 
		address = append(address, scanner.Text())
	}
	fmt.Println(address)
	m := gomail.NewMessage()
	m.SetHeader("From", "wenchangshou@163.com")
	m.SetHeader("To", address...)
	m.SetHeader("Subject", "好玩的docker!")
	m.SetBody("text/html", "别偷懒了，该干活了!")
	d := gomail.Dialer{Host: "smtp.163.com", Port: 465, Username: "wenchangshou@163.com", Password: "XXXXXX", SSL: true}
	if err := d.DialAndSend(m); err != nil {
		fmt.Println(err)
		return
	}

}

var knt int
var f MQTT.MessageHandler = func(client MQTT.Client, msg MQTT.Message) {
	fmt.Printf("MSG: %s\n", msg.Payload())
	if string(msg.Payload()) == "update" {
		clearDocker()
		pullDocker()
		sendMail()
	}
	text := fmt.Sprintf("this is result msg #%d!", knt)
	knt++
	token := client.Publish("nn/result", 0, false, text)
	token.Wait()
}

func main() {
	knt = 0
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt, syscall.SIGTERM)

	opts := MQTT.NewClientOptions().AddBroker("tcp://wy.wcs91.com:1883")
	opts.SetClientID("mac-go")
	opts.SetDefaultPublishHandler(f)
	topic := "/docker/ctrl/#"

	opts.OnConnect = func(c MQTT.Client) {
		if token := c.Subscribe(topic, 0, f); token.Wait() && token.Error() != nil {
			panic(token.Error())
		}
	}
	client := MQTT.NewClient(opts)
	if token := client.Connect(); token.Wait() && token.Error() != nil {
		panic(token.Error())
	} else {
		fmt.Printf("Connected to server\n")
	}
	<-c
}
